package com.wtwd.campus.wx.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.utils.RequestClient;
import org.jeewx.api.core.exception.WexinReqException;
import org.jeewx.api.core.req.model.message.TemplateMessageSendResult;
import org.jeewx.api.wxbase.wxtoken.JwTokenAPI;
import org.jeewx.api.wxsendmsg.JwSendTemplateMsgAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @Author ldaoliang
 * @Date create in 17:55 2021/6/17
 * @Description
 */
public class WxUtils {

    private static final Logger logger = LoggerFactory.getLogger(WxUtils.class);

    //瑞翼
    private static final String WX_APP_ID_RY = "wxe127a0c95ac1911a";
    private static final String WX_APP_SECRET_RY = "a270e9cf5783c5e9902d61e195996e4a";

    //创维
    private static final String WX_APP_ID_CW = "wxb27a83d55006efb3";
    private static final String WX_APP_SECRET_CW = "d3f9479fc8d45800a3b08ef8878f0bd8";


    //小湃
    private static final String WX_APP_ID_XB = "wxe7a4758901947953";
    private static final String WX_APP_SECRET_XB = "f57191a4acbfb8294f864d8e85ba2303";


    /**
     * 平台公众号在授权模式下，根据code获取AccessToken和OpenId
     *
     * @param code
     * @return
     * @throws Exception
     */
    public static Map<String, String> getAccessTokenAndOpenId(String code) throws Exception {
        Map<String, String> map = new HashMap<>();
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constants.WX_APP_ID + "&secret=" + Constants.WX_APP_SECRET + "&code=" + code + "&grant_type=authorization_code";
        String res = RequestClient.createRequest().get(requestUrl).build().send();
        JSONObject json = JSON.parseObject(res);
        logger.info("获取用户授权后的信息：" + res);
        if (null != json.get("openid") && null != json.get("access_token")) {
            map.put("accessToken", json.getString("access_token"));
            map.put("openId", json.getString("openid"));
        }
        return map;
    }

    /**
     * 获取微信Token
     *
     * @return
     * @throws WexinReqException
     */
    public static String getAccessToken() throws WexinReqException {
        String strToken = JwTokenAPI.getAccessToken(Constants.WX_APP_ID, Constants.WX_APP_SECRET);
        return strToken;
    }

    /**
     * 获取微信Token(瑞翼)
     *
     * @return
     * @throws WexinReqException
     */
    public static String getAccessTokenRy() throws WexinReqException {
        String strToken = JwTokenAPI.getAccessToken(WX_APP_ID_RY, WX_APP_SECRET_RY);
        return strToken;
    }

    /**
     * 获取微信token创维
     */

    public static String getAccessTokenCW() throws WexinReqException {
        String strToken = JwTokenAPI.getAccessToken(WX_APP_ID_CW, WX_APP_SECRET_CW);
        return strToken;
    }

    /**
     * 获取微信token小湃
     * @return
     * @throws WexinReqException
     */
    public static String getAccessTokenXB() throws WexinReqException {
        String strToken = JwTokenAPI.getAccessToken(WX_APP_ID_XB, WX_APP_SECRET_XB);
        return strToken;
    }

    /**
     * 获取微信Token（喜马拉雅）
     *
     * @return
     * @throws WexinReqException
     */
    public static String getAccessTokenXmly() throws WexinReqException {
        String strToken = JwTokenAPI.getAccessToken(Constants.WX_APP_ID_XMLY, Constants.WX_APP_SECRET_XMLY);
        return strToken;
    }

    public static String getOpenId(String code) throws Exception {
        String openId = "openid";
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constants.WX_APP_ID +
                "&secret=" + Constants.WX_APP_SECRET + "&code=" + code + "&grant_type=authorization_code";
        String openid = null;
        String res = RequestClient.createRequest().get(requestUrl).build().send();
        JSONObject json = JSON.parseObject(res);
        if (null != json.get(openId)) {
            openid = json.get(openId).toString();
        }
        return openid;
    }

    /**
     * 喜马拉雅
     *
     * @param code
     * @return
     * @throws Exception
     */
    public static String getOpenId2(String code) throws Exception {
        String openId = "openid";
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constants.WX_APP_ID_XMLY +
                "&secret=" + Constants.WX_APP_SECRET_XMLY + "&code=" + code + "&grant_type=authorization_code";
        String openid = null;
        String res = RequestClient.createRequest().get(requestUrl).build().send();
        JSONObject json = JSON.parseObject(res);
        if (null != json.get(openId)) {
            openid = json.get(openId).toString();
        }
        return openid;
    }

    /**
     * 瑞翼
     *
     * @param code
     * @return
     * @throws Exception
     */
    public static String getOpenId3(String code) throws Exception {
        String openId = "openid";
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WX_APP_ID_RY +
                "&secret=" + WX_APP_SECRET_RY + "&code=" + code + "&grant_type=authorization_code";
        String openid = null;
        String res = RequestClient.createRequest().get(requestUrl).build().send();
        JSONObject json = JSON.parseObject(res);
        if (null != json.get(openId)) {
            openid = json.get(openId).toString();
        }
        return openid;
    }


    /**
     * 创维
     */
    public static String getOpenId4(String code) throws Exception {
        String openId = "openid";
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WX_APP_ID_CW +
                "&secret=" + WX_APP_SECRET_CW + "&code=" + code + "&grant_type=authorization_code";
        String openid = null;
        String res = RequestClient.createRequest().get(requestUrl).build().send();
        JSONObject json = JSON.parseObject(res);
        if (null != json.get(openId)) {
            openid = json.get(openId).toString();
        }
        return openid;
    }

    /**
     * 小湃
     */
    public static String getOpenId5(String code) throws Exception {
        String openId = "openid";
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WX_APP_ID_XB +
                "&secret=" + WX_APP_SECRET_XB + "&code=" + code + "&grant_type=authorization_code";
        String openid = null;
        String res = RequestClient.createRequest().get(requestUrl).build().send();
        JSONObject json = JSON.parseObject(res);
        if (null != json.get(openId)) {
            openid = json.get(openId).toString();
        }
        return openid;
    }


    /**
     * 获取用户信息（沃特平台）
     *
     * @param accessToken
     * @return
     * @throws Exception
     * @Param openId
     */
    public static Map<String, Object> getUserInfo(String accessToken, String openId) {
        String nickName = "";
        String headImg = "";
        String res = null;
        try {
            /* String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";*/
            String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
            res = RequestClient.createRequest().get(requestUrl).build().send();
            logger.info("获取的微信用户的原始信息：".concat(res));
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject json = JSON.parseObject(res);
        if (null != json.get("nickname") && null != json.get("headimgurl")) {
            nickName = (String) json.get("nickname");
            headImg = (String) json.get("headimgurl");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("name", nickName);
        map.put("headImg", headImg);
        return map;
    }

    /**
     * 获取用户信息(瑞翼)
     *
     * @param openId
     * @return
     * @throws Exception
     */
    public static List<String> getUserInfoRy(String openId) {
        String nickName = "";
        String headImg = "";
        String accessToken = null;
        String res = null;
        try {
            accessToken = getAccessTokenRy();
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
            res = RequestClient.createRequest().get(requestUrl).build().send();
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject json = JSON.parseObject(res);
        if (null != json.get("nickname") && null != json.get("headimgurl")) {
            nickName = (String) json.get("nickname");
            headImg = (String) json.get("headimgurl");
        }
        List<String> list = new ArrayList<>();
        list.add(0, nickName);
        list.add(1, headImg);
        return list;
    }


    /**
     * 获取长虹用户信息
     */
    public static List<String> getUserInfoCW(String openId) {
        String nickName = "";
        String headImg = "";
        String accessToken = null;
        String res = null;
        try {
            accessToken = getAccessTokenCW();
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
            res = RequestClient.createRequest().get(requestUrl).build().send();
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject json = JSON.parseObject(res);
        if (null != json.get("nickname") && null != json.get("headimgurl")) {
            nickName = (String) json.get("nickname");
            headImg = (String) json.get("headimgurl");
        }
        List<String> list = new ArrayList<>();
        list.add(0, nickName);
        list.add(1, headImg);
        return list;
    }


    /**
     * 获取用户信息（喜马拉雅）
     *
     * @param openId
     * @return
     * @throws Exception
     */
    public static List<String> getUserInfoXmly(String openId) throws Exception {
        String accessToken = getAccessToken();
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        String res = RequestClient.createRequest().get(requestUrl).build().send();
        JSONObject json = JSON.parseObject(res);
        String nickName = "";
        String headImg = "";
        if (null != json.get("nickname") && null != json.get("headimgurl")) {
            nickName = (String) json.get("nickname");
            headImg = (String) json.get("headimgurl");
        }
        List<String> list = new ArrayList<>();
        list.add(0, nickName);
        list.add(1, headImg);
        return list;
    }


    public static boolean pushMsg(TemplateMessageSendResult template) {
        boolean isSend = false;
        try {
            String accessToken = WxUtils.getAccessToken();
            logger.info("accessToken:{}", accessToken);
            String s = JwSendTemplateMsgAPI.sendTemplateMsg(accessToken, template);
            logger.info("发送消息模板成功:{}", s);
            isSend = true;
        } catch (WexinReqException e) {
            logger.info("发送消息模板失败:{}", e);
        }
        return isSend;
    }

    public static boolean pushMsgRy(TemplateMessageSendResult template) {
        boolean isSend = false;
        try {
            String accessToken = WxUtils.getAccessTokenRy();
            logger.info("accessToken:{}", accessToken);
            String s = JwSendTemplateMsgAPI.sendTemplateMsg(accessToken, template);
            logger.info("发送瑞翼消息模板成功:{}", s);
            isSend = true;
        } catch (WexinReqException e) {
            logger.info("发送瑞翼消息模板失败:{}", e);
        }
        return isSend;
    }


    /**
     * 推送模板消息到创维
     *
     * @param template
     * @return
     */
    public static boolean pushMsgCW(TemplateMessageSendResult template) {
        boolean isSend = false;
        try {
            String accessToken = WxUtils.getAccessTokenCW();
            logger.info("accessToken:{}", accessToken);
            String s = JwSendTemplateMsgAPI.sendTemplateMsg(accessToken, template);
            logger.info("发送创维消息模板成功:{}", s);
            isSend = true;
        } catch (WexinReqException e) {
            logger.info("发送创维消息模板失败:{}", e);
        }
        return isSend;
    }

    /**
     * 推送模板消息到小湃
     *
     * @param template
     * @return
     */
    public static boolean pushMsgXB(TemplateMessageSendResult template) {
        boolean isSend = false;
        try {
            String accessToken = WxUtils.getAccessTokenXB();
            logger.info("accessToken:{}", accessToken);
            String s = JwSendTemplateMsgAPI.sendTemplateMsg(accessToken, template);
            logger.info("发送创维消息模板成功:{}", s);
            isSend = true;
        } catch (WexinReqException e) {
            logger.info("发送创维消息模板失败:{}", e);
        }
        return isSend;
    }


    public static void main(String[] args) throws Exception {
        /*System.out.println(getAccessToken());*/
       /* List<String> aa = getUserInfo("obdQT6MNVIZ9KHVIJraHs94-dqco");
        System.out.println(aa.toString());*/
    }
}
